<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="ctxPath" value="${pageContext.request.contextPath}"/>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <title>用户列表</title>
  <link rel="stylesheet" href="${ctxPath}/layuiadmin/layui/css/layui.css" media="all">
  <link rel="stylesheet" href="${ctxPath}/layuiadmin/style/admin.css" media="all">
  <style>
    body{margin: 10px;}
    .demo-carousel{height: 200px; line-height: 200px; text-align: center;}
    input[readonly]{
    }
  </style>
</head>
<body>
<table class="layui-hide" id="demo" lay-filter="test"></table>
 
<script type="text/html" id="toolBar">
  <a class="layui-btn layui-btn-normal layui-btn-xs layui-btn-radius" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs layui-btn-radius" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>
<script type="text/html" id="headToolBar">
<div class="layui-btn-group">
  <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="add">
    <i class="layui-icon">&#xe654;</i>
  </button>
  <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="update">
    <i class="layui-icon">&#xe642;</i>
  </button>
  <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="delete">
    <i class="layui-icon">&#xe640;</i>
  </button>
  <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" lay-event="search">
    <i class="layui-icon">&#xe615;</i>
  </button>
</div>
</script>

 <script src="${ctxPath}/layuiadmin/layui/layui.js"></script> 
<script src="${ctxPath}/js/jquery-1.11.1.min.js"></script>


<script>
var r=Math.floor(Math.random()*6);
 
layui.use(
	['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider'], 
	function(){
	  var laydate = layui.laydate //日期
	  ,laypage = layui.laypage //分页
	  ,layer = layui.layer //弹层
	  ,table = layui.table //表格
	  ,carousel = layui.carousel //轮播
	  ,upload = layui.upload //上传
	  ,element = layui.element //元素操作
	  ,slider = layui.slider //滑块
	  ,admin = layui.admin
	  ,form = layui.form;
	  
	  //layer.msg('用户列表',{icon:6,time:2000,offset:'20px'});
  
  //{ps} 监听Tab切换
  element.on('tab(demo)', function(data){
    layer.tips('切换了 '+ data.index +': '+ this.innerHTML, this, {
      tips: 1
    });
  });
  
  //{ps} 执行一个 table 实例
  var ran = Math.random();
  table.render({
    elem: '#demo'
    ,height: 'full-100'
    ,url: '${ctxPath}/User/jsonList?ran='+ ran //数据接口
    ,title: '用户表'
    ,page: true     //{ps} 开启分页
    ,toolbar: '#headToolBar' //{ps} 开启工具栏，此处显示默认图标，可以自定义模板，详见文档
    ,totalRow: false //{ps} 开启合计行
    ,limit:1000
    ,limits:[10,20,50,100,200,500,1000,2000]
    ,cellMinWidth:80
    ,cols: [[
      {type: 'checkbox'},
      {field: 'id', title: 'ID', width:100, sort: true},
      {field: 'account', title: '用户名', width:120,sort:true},
      {field: 'password', title: '密码', width:100,hide:true, edit:'text'},
      {field: 'nickName', title: '昵称', width:100, edit:'text'},
      {field: 'no', title: '工号',sort:true, width:120, edit:'text'},
      {field: 'sex', title: '性别',sort:true, width:80},
      {field: 'roleName', title: '角色名称',sort:true, width:120},
      {field: 'updateDate', title: '更新日期',sort:true,hide:true, width:200},
      {field: 'createDate', title: '创建日期',sort:true, width:200},
      {fixed: 'right', title:'操作', align:'center', toolbar: '#toolBar',minWidth:120}
    ]]
    ,initSort:{
        field:'createDate',
        type:'asc',
    }
    ,text:'对不起，加载出现异常！请联系小蓝解决！'
   	,done: function(res, curr, count){
		 if (res.count == 0) {
              $(".layui-none").hide();//隐藏无数据
              $(".layui-table-page").hide();//隐藏分页
          }
	  }
  });
  
  //{ps} 监听头工具栏事件
  table.on('toolbar(test)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id)
    ,data = checkStatus.data; //获取选中的数据
    switch(obj.event){
      case 'add':
        layer.open({
            type: 2
            ,content: '${ctxPath}/User/viewAddUser'
            ,shade:0
            ,shadeClose: false
            ,moveOut:true
            ,area: ['80%', '80%']
            ,maxmin: true
            ,anim:r
            ,title:'创建'
          });
      break;
      case 'update':
        if(data.length === 0){
        	layer.msg('请选择一行',{icon:2,time:2000,offset:'20px'});
        }  else if(data.length > 1){
        	layer.msg('只能编辑一行',{icon:2,time:2000,offset:'20px'});
        }  else {
        	/* for(var i=0;i<=(checkStatus.data).length;i++){
        		layer.alert(JSON.stringify(checkStatus.data[0]));
        	} */
           editUser( checkStatus.data[0].id ); 
        }
      break;
      case 'delete':
        if(data.length === 0){
        	layer.msg('请选择一行',{icon:2,time:2000,offset:'20px'});
        } else{
        	
        	layer.confirm('删除这些用户吗', function(index){
        		var s='';
            	for(var i=0;i<(checkStatus.data).length;i++){
            		s=s+JSON.stringify(checkStatus.data[i]['account'])+",";
            		delUser( checkStatus.data[i].id );
        		}
            	layer.msg('删除[id]:'+s,{icon:1,time:2000,offset:'20px'});
              });
        }
      break;
      case 'search':
    	  layer.msg('按键ctrl+F,进行搜索',{icon:3,time:4000,offset:'20px'});
   	  break;
    };
  });
  
  //{ps} 监听行工具事件
  table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
    var data = obj.data     //获得当前行数据
    , layEvent = obj.event; //获得 lay-event 对应的值
    if(layEvent === 'detail'){
    	layer.msg('查看[id]:'+data.id,{icon:6,time:2000,offset:'20px'});
    } else if(layEvent === 'del'){
      	layer.confirm('删除\''+data.id+'\'用户吗', function(index){
    	layer.msg('删除[id]:'+data.id,{icon:1,time:2000,offset:'20px'});
		delUser( data['id'] );
      });
    } else if(layEvent === 'edit'){
    	//{1} 获取一个用户, 通过 ajax 来获取。
    	//  data['id']: 表格上面的 id 值。
		editUser( data['id'] );
    }
  });
  
//监听单元格编辑
  table.on('edit(test)', function(obj){
    var value = obj.value //得到修改后的值
    ,data = obj.data //得到所在行所有键值
    ,field = obj.field; //得到字段
    $.ajax({
    			url:'${ctxPath}/User/getUser', /* 数据接口 */
    			type:'post',
    			data:{id:data.id},
    			dataType:'json',
    			success:function( resp ){
    				if( resp['result']=='success' ){
    					var _user =resp['user'];
    					_user[field]=value;
    					console.log( _user );
    					$.ajax({
    						url:'${ctxPath}/User/saveUser',
    						type:'post',
    						data:_user,
    						dataType:'json',
    						success:function( resp ){
    							var result = resp['result'];
    							//{ps} 关闭弹窗
    							layer.closeAll();
    							if(result=='success'){
    								layer.msg('更新用户:'+ resp['account'] +'成功',{icon:1,time:2000,offset:'20px'});
    							}else{
    								layer.msg('更新用户:'+ resp['account'] +'失败, 原因: '+ resp['cause'],{icon:2,time:2000,offset:'20px'});
    							}
    						}
    					});
    				}else{
    					layer.msg('访问数据错误。');
    				}
    			}
    		});
  });
  
//监听行双击事件
  table.on('rowDouble(test)', function(obj){
	  editUser( obj.data.id );
  });
  
});


</script>


<!-- {ps} 编写我们的 js 代码! -->
<script>
function editUser( userId ){
	$.ajax(
		{
			url:'${ctxPath}/User/getUser', /* 数据接口 */
			type:'post',
			data:{id:userId},
			dataType:'json',
			success:function( resp ){
				if( resp['result']=='success' ){
					console.log( resp['user'] );
					onRecvMsg( resp );   //显示对话框
				}else{
					layer.msg('访问数据错误。');
				}
			}
		}
	);
}

//{ps} 当接收到后台发来的 用户数据时，触发该方法。
//     这一个方法会传一个 json 进来。
function onRecvMsg( json ){
	var HTML="<div class=\"layui-fluid\">"+
	"<div class=\"layui-card\">"+
	"<div class=\"layui-card-header\">"+json['user']['nickName']+"</div>"+
	"<div class=\"layui-card-body\" style=\"padding: 15px;\">"+
	"<form class=\"layui-form\" action=\"\" lay-filter=\"component-form-group\">"+
	"<div class=\"layui-col-md6\">"+
		"<div class=\"layui-form-item\">"+
		"<label class=\"layui-form-label\">用户ID</label>"+
		"<div class=\"layui-input-inline\">"+
		"<input value='"+json['user']['id']+"' type=\"text\" id=\"id\" name=\"id\" lay-verify=\"required\" placeholder=\""+json['user']['nickName']+"的ID\" autocomplete=\"off\" class=\"layui-input\" readonly>"+
		"</div>"+
		"<div class=\"layui-form-mid layui-word-aux\">只读</div>"+
		"</div>"+
	"</div>"+
	"<div class=\"layui-col-md6\">"+
		"<div class=\"layui-form-item\">"+
		"<label class=\"layui-form-label\">用户名</label>"+
		"<div class=\"layui-input-inline\">"+
		"<input value='"+json['user']['account']+"' type=\"text\" id=\"account\" name=\"account\" lay-verify=\"required\" placeholder=\""+json['user']['nickName']+"的用户名\" autocomplete=\"off\" class=\"layui-input\" readonly>"+
		"</div>"+
		"<div class=\"layui-form-mid layui-word-aux\">只读</div>"+
		"</div>"+
	"</div>"+
	"<div class=\"layui-col-md6\">"+
		"<div class=\"layui-form-item\">"+
		"<label class=\"layui-form-label\">用户密码</label>"+
		"<div class=\"layui-input-inline\">"+
		"<input value='"+json['user']['password']+"' id=\"password\" type=\"text\" name=\"password\" lay-verify=\"required\" placeholder=\""+json['user']['nickName']+"的密码\" autocomplete=\"off\" class=\"layui-input\">"+
		"</div>"+
		"</div>"+
	"</div>"+
	"<div class=\"layui-col-md6\">"+
		"<div class=\"layui-form-item\">"+
		"<label class=\"layui-form-label\">用户昵称</label>"+
		"<div class=\"layui-input-inline\">"+
		"<input value='"+json['user']['nickName']+"' type=\"text\" id=\"nickName\" name=\"nickName\" lay-verify=\"required\" placeholder=\""+json['user']['nickName']+"的昵称\" autocomplete=\"off\" class=\"layui-input\">"+
		"</div>"+
		"</div>"+
	"</div>"+
	"<div class=\"layui-col-md6\">"+
		"<div class=\"layui-form-item\">"+
		"<label class=\"layui-form-label\">用户工号</label>"+
		"<div class=\"layui-input-inline\">"+
		"<input value='"+json['user']['no']+"' type=\"text\" id=\"no\" name=\"no\" lay-verify=\"required\" placeholder=\""+json['user']['nickName']+"的工号\" autocomplete=\"off\" class=\"layui-input\">"+
		"</div>"+
		"</div>"+
	"</div>"+
	"<div class=\"layui-col-md6\">"+
		"<div class=\"layui-form-item\">"+
		"<div class=\"layui-inline\">"+
		"<label class=\"layui-form-label\">用户角色</label>"+
		"<div class=\"layui-input-inline\">"+
		"<select id=\"roleId\" name=\"roleId\" lay-verify=\"required\" lay-search=\"\">"+
		"<option value=\"\">直接选择或搜索选择</option>";
		var arr=['酒店经理','酒店前台','保洁人员','维修人员','后勤人员','公司财务']
		for(var i=1;i<=6;i++){
			HTML+="<option";
			if(json['user']['roleId']==i){
				HTML+=" selected";
			}
			HTML+=" value=\""+i+"\">"+arr[(i-1)]+"</option>";
		}
		HTML+=
		"</select>"+
		"</div>"+
		"</div>"+
		"</div>"+
	"</div>"+
	"<div class=\"layui-form-item\">"+
	"<label class=\"layui-form-label\">性别</label>"+
	"<div class=\"layui-input-block\">";
	var arr2=['男','女'];
	for(var i=0;i<2;i++){
		HTML+="<input type=\"radio\" name=\"sex\" value=\""+arr2[i]+"\" title=\""+arr2[i]+"\"";
		if(json['user']['sex']==arr2[i]){
			HTML+=" checked=\"\">";
		}else{
			HTML+=">";
		}
	}
	HTML+="</div>"+
	"</div> "+
	"</form>"+
	"</div>"+
	"</div>"+
	"</div>";
	layer.open({
         type: 1
         ,title: '编辑用户'      //显示标题栏
         ,closeBtn: false
         ,skin: 'layui-layer-rim'
         ,area: ['80%','80%']
         ,shadeClose: true
         ,id: 'LAY_layuipro'   //设定一个 id, 防止重复弹出
         ,btn: ['保存用户', '关闭']  //{ps} 两个按钮
         ,btnAlign: 'c'        //居中对齐
         ,moveType: 1          //拖拽模式, 0 或者 1
         ,content: HTML        //这是上面生成的表格 html 代码
         ,anim:r
         ,yes: function(){
        	   //{1} 当点击 '保存用户' 时候, 调用这个函数
               saveUser();       //保存用户(写到数据库)
               //不建议这里关闭, 等消息回来才做。
               //layer.closeAll(); //关闭对话框
         }
         ,success: function( layero ){
        	 //重新渲染
        	 layui.use('form', function(){
                 var form = layui.form;
                 form.render();
             });
         }
	});
}    //ENDING {onRecvMsg}

//{1} 清除页面中的 maketable
//{2} 除页面中的 showBox

//{ps}你要获取的项目
var items = [
	"id", "account", "password", "nickName",
	"sex", "roleId", "no"
];

//{ps} 抓取表单数据
function pickData(){
	var obj = {};
	for( var i=0; i<items.length; i++ ){
		var val = $("#"+ items[i]).val();
		obj[ items[i] ] = val;
	}
	var sex=$("input[name='sex']:checked").val();
	obj["sex"]=sex;
	return obj;
}

/* 
 *  函数:    saveUser
 *  提交数据, 通过 ajax 对象。
 *	提交地址: /User/saveUser
 *  数据返回: 
    {
	    "result":"success",
	    "account":"andy"
	}
 */

function saveUser(){
	//{1}获取表单数据。
	var _user = pickData();
	console.log("Data:"+ _user );
	//(2)使用 ajax 提交数据
	//(3)地址: /User/saveUser
	$.ajax({
		url:'${ctxPath}/User/saveUser',
		type:'post',
		data:_user,
		dataType:'json',
		success:function( resp ){
			var result = resp['result'];
			//{ps} 关闭弹窗
			layer.closeAll();
			if(result=='success'){
				layer.msg('更新用户：'+resp['account']+'成功',{icon:1,time:2000,offset:'20px'});
				//{1} 1.0秒重新刷新页面。
				setTimeout( reloadPage, 1000 );
			}else{
				layer.msg('更新用户:'+resp['account'] +'失败, 原因:'+ resp['cause'],{icon:2,time:2000,offset:'20px'});
			}
		}
	});
}

function reloadPage(){
	window.location = '${ctxPath}/User/viewList';
}

function delUser( _id ){
	$.ajax({
		url:'${ctxPath}/User/delUser',
		type:'post',
		data:{id:_id},
		dataType:'json',
		success:function( resp ){
			var result = resp['result'];
			//{ps} 关闭弹窗
			layer.closeAll();
			if(result=='success'){
				layer.msg('删除用户：'+_id+'成功',{icon:1,time:2000,offset:'20px'});
				//{1} 1.0秒重新刷新页面。
				setTimeout( reloadPage, 1000 );
			}else{
				layer.msg('删除用户:'+_id+'失败, 原因:'+ resp['cause'],{icon:2,time:2000,offset:'20px'});
			}
		}
	});
}

/* //执行一个轮播实例
carousel.render({
  elem: '#test1'
  ,width: '100%' //设置容器宽度
  ,height: 200
  ,arrow: 'none' //不显示箭头
  ,anim: 'fade' //切换动画方式
});

//将日期直接嵌套在指定容器中
var dateIns = laydate.render({
  elem: '#laydateDemo'
  ,position: 'static'
  ,calendar: true //是否开启公历重要节日
  ,mark: { //标记重要日子
    '0-10-14': '生日'
    ,'2018-08-28': '新版'
    ,'2018-10-08': '神秘'
  } 
  ,done: function(value, date, endDate){
    if(date.year == 2017 && date.month == 11 && date.date == 30){
      dateIns.hint('一不小心就月底了呢');
    }
  }
  ,change: function(value, date, endDate){
    layer.msg(value)
  }
});

//分页
laypage.render({
  elem: 'pageDemo' //分页容器的id
  ,count: 8        //总页数
  ,skin: '#1E9FFF' //自定义选中色值
  //,skip: true    //开启跳页
  ,jump: function(obj, first){
    if(!first){
      layer.msg('第'+ obj.curr +'页', {offset: 'b'});
      alert( "TTTTTTTTT" );
    }
  }
});

//上传
upload.render({
  elem: '#uploadDemo'
  ,url: '' //上传接口
  ,done: function(res){
    console.log(res)
  }
});

slider.render({
  elem: '#sliderDemo'
  ,input: true //输入框
}); */
</script>

</body>
</html>        

